<template>
  <PageTabelLayout>
    <template #pageHeader>
      <div class="search-form isheader" v-if="headerShow">
        <div>
          <a-form size="mini" :model="searchData" layout="inline">
            <a-form-item label="所属公司" :rules="[{ required: true }]">
              <a-cascader
                :options="pageData.corporateList"
                v-model="searchData.firmId"
                allow-clear
                class="bacClass"
                :loading="pageData.corporateLoading"
                popup-container="html"
              />
            </a-form-item>
            <a-form-item label="仓库类型" :rules="[{ required: true }]">
              <a-select
                popup-container="html"
                class="bacClass"
                :style="{ width: '10rem' }"
                @change="companyChange"
                placeholder=""
                v-model="searchData.whTypeName"
                allow-clear
              >
                <a-option v-for="item in whTypeList" :value="item.typeName">
                  {{ item.typeName }}
                </a-option>
              </a-select>
            </a-form-item>
            <a-form-item label="仓库名称" :rules="[{ required: true }]">
              <a-select
                popup-container="html"
                class="bacClass"
                :style="{ width: '10rem' }"
                v-model="searchData.wh"
                allow-clear
                @focus="ckmcFocus1"
                @change="warehouseId2"
              >
                <a-option v-for="item in whList" :value="item.warehouseName">
                  {{ item.warehouseName }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-form>
        </div>
        <div class="my-tool-bar">
          <Toolbar
            :items="[
              `${permissionStore.hasPermisson('ckqy.cx') ? '查询' : ''}`,
              `${permissionStore.hasPermisson('ckqy.xz') ? '新增' : ''}`,
              `${permissionStore.hasPermisson('ckqy.sc') ? '删除' : ''}`,
              `${permissionStore.hasPermisson('ckqy.dc') ? '导出' : ''}`,
              `${permissionStore.hasPermisson('ckqy.dr') ? '导入' : ''}`,
            ]"
            @add="addHandler"
            @del="deleteHandler"
            @select="selectHandler"
            @export="exports"
            @import="importHandler"
            @excel="downloadHandler"
          >
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
    </template>
    <template #pageTabel>
      <AgGridVuesCopys
        :rowHeight="33"
        :headerHeight="33"
        :suppressCopyRowsToClipboard="true"
        :suppressDragLeaveHidesColumns="true"
        rowSelection="multiple"
        @grid-ready="gridReady"
        @columnResized="onColumnResized"
        @columnMoved="onColumnMoved"
        @columnVisible="onColumnVisible"
        style="height: calc(100% - 45px)"
        :defaultColDef="defaultColDef"
        class="ag-theme-alpine"
        :rowData="table.dataList"
        :columnDefs="tc"
        :localeText="localeText1"
      ></AgGridVuesCopys>
      <paginationCopys
        :page-size-options="pagingList1"
        v-if="isIDs == 1"
        :total="total"
        show-total
        show-jumper
        show-page-size
        :page-size="pagination.pageSize"
        :current="pagination.page"
        @change="PageSize"
        @page-size-change="change1"
        style="justify-content: center"
      />
    </template>

    <a-drawer
      ok-text="保存"
      cancel-text="关闭"
      :drawer-style="{ zIndex: 9999 }"
      :mask-closable="false"
      :width="400"
      :visible="pageData.showAdd"
      unmountOnClose
      @ok="sideOk"
      @cancel="pageData.showAdd = false"
    >
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" layout="horizontal" :model="dataForm">
          <a-form-item
            label-col-flex="80px"
            label="所属公司"
            field="firmId"
            :rules="[{ required: true, message: '所属公司必填' }]"
            :validate-trigger="['change', 'blur']"
            :disabled="pageData.sideTitle == '修改仓库' ? true : false"
          >
            <a-cascader
              :options="pageData.corporateList"
              @change="corporateChange"
              v-model="dataForm.firmId"
              allow-clear
              class="bacClass"
              ref="corporateRef"
              :loading="pageData.corporateLoading"
              popup-container="html"
            />
          </a-form-item>
          <a-form-item
            label-col-flex="80px"
            label="仓库类型"
            field="warehouseTypeName"
            :rules="[{ required: true, message: '仓库类型必填' }]"
            :validate-trigger="['change', 'blur']"
            :disabled="pageData.sideTitle == '修改仓库' ? true : false"
          >
            <a-select
              popup-container="html"
              class="bacClass"
              @change="companyChange1"
              placeholder=""
              v-model="dataForm.warehouseTypeName"
              allow-clear
            >
              <a-option v-for="item in whTypeList" :value="item.typeName">
                {{ item.typeName }}
              </a-option>
            </a-select>
          </a-form-item>
          <a-form-item
            label-col-flex="80px"
            label="仓库名称"
            field="warehouseName"
            :rules="[{ required: false, message: '仓库名称必填' }]"
            :validate-trigger="['change', 'blur']"
            :disabled="pageData.sideTitle == '修改仓库' ? true : false"
          >
            <a-select
              popup-container="html"
              class="bacClass"
              placeholder=""
              v-model="dataForm.warehouseName"
              allow-clear
              @focus="ckmcFocus"
              @change="warehouseId1"
            >
              <a-option v-for="item in whList" :value="item.warehouseName">
                {{ item.warehouseName }}
              </a-option>
            </a-select>
          </a-form-item>
          <a-form-item
            label-col-flex="80px"
            label="区域编号"
            field="areaCode"
            :rules="[{ validator: isChiese }, { required: true, message: '区域编号必填' }]"
            :validate-trigger="['change', 'blur']"
          >
            <a-input v-model="dataForm.areaCode" class="input-demo bacClass" @blur="inputBlur" />
          </a-form-item>
          <a-form-item
            label-col-flex="80px"
            label="区域名称"
            field="areaName"
            :rules="[{ required: true, message: '区域名称必填' }]"
            :validate-trigger="['change', 'blur']"
          >
            <a-input class="bacClass" v-model="dataForm.areaName" />
          </a-form-item>
          <a-form-item label-col-flex="80px" label="备注" field="remark">
            <a-textarea
              class="bacClass"
              v-model="dataForm.remark"
              :max-length="400"
              allow-clear
              show-word-limit
            />
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
    <a-modal
      ok-text="保存"
      cancel-text="关闭"
      :drawer-style="{ zIndex: 9999 }"
      :maskClosable="false"
      :width="400"
      :ok-loading="pageData.pageLoading"
      :visible="pageData.showAdd1"
      unmountOnClose
      @ok="sideOks"
      @cancel="pageData.showAdd1 = false"
    >
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" layout="vertical" :model="dataForm">
          <a-form-item
            label="所属公司"
            field="firm"
            :rules="[{ required: true, message: '所属公司必填' }]"
            :validate-trigger="['change', 'blur']"
          >
            <a-select
              popup-container="html"
              class="bacClass"
              @change="companyChange1"
              placeholder=""
              v-model="dataForm.firm"
              allow-clear
            >
              <a-option v-for="item in companyList" :value="item.id">
                {{ item.typeName }}{{ item.typeName == '' ? '' : '-' }}{{ item.firmName }}
              </a-option>
            </a-select>
          </a-form-item>
          <a-form-item
            label="仓库类型"
            field="warehouseTypeName"
            :rules="[{ required: true, message: '仓库类型必填' }]"
            :validate-trigger="['change', 'blur']"
          >
            <a-select
              popup-container="html"
              class="bacClass"
              @change="companyChange1"
              placeholder=""
              v-model="dataForm.warehouseTypeName"
              allow-clear
            >
              <a-option v-for="item in whTypeList" :value="item.typeName">
                {{ item.typeName }}
              </a-option>
            </a-select>
          </a-form-item>
          <a-form-item
            label="仓库名称"
            field="warehouseName"
            :rules="[{ required: true, message: '仓库名称必填' }]"
            :validate-trigger="['change', 'blur']"
          >
            <a-select
              popup-container="html"
              class="bacClass"
              placeholder=""
              v-model="dataForm.warehouseName"
              allow-clear
              @focus="ckmcFocus"
              @change="warehouseId1"
            >
              <a-option v-for="item in whList" :value="item.warehouseName">
                {{ item.warehouseName }}
              </a-option>
            </a-select>
          </a-form-item>
        </a-form>
      </div>
    </a-modal>
    <a-modal
      :visible="visible"
      @ok="handleOk"
      @cancel="handleCancel"
      okText="打印"
      cancelText="关闭"
      unmountOnClose
    >
      <template #title> 打印二维码</template>
      <div id="warehouse">
        <QrcodeVue :value="qrData.code" style="width: 110px; height: 110px"></QrcodeVue>
        <div style="display: inline-block; vertical-align: top; margin-left: 15px; width: 200px">
          <span
            >公&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;司: {{ decodeURI(qrData.gcName) }}</span
          >
          <br />
          <span>仓库名称: {{ decodeURI(qrData.ckName) }}</span>
          <br />
          <span>仓库类型: {{ decodeURI(qrData.ckType) }}</span>
          <br />
          <span>区域编号: {{ decodeURI(qrData.areaCode) }}</span>
          <br />
          <span>区域名称: {{ decodeURI(qrData.areaName) }}</span>
          <br />
        </div>
      </div>
    </a-modal>
  </PageTabelLayout>
  <a-modal
    :visible="visible1"
    @ok="print1"
    @cancel="handleCancel1"
    okText="打印"
    cancelText="关闭"
    unmountOnClose
  >
    <template #title> 打印二维码</template>
    <div id="storagePrint">
      <div v-for="item in printList as any">
        <QrcodeVue :value="item.code" style="width: 110px; height: 110px"></QrcodeVue>
        <div style="display: inline-block; vertical-align: top; margin-left: 15px; width: 200px">
          <span>工厂名称： {{ decodeURI(item.gcName) }}</span>
          <br />
          <span>仓库名称： {{ decodeURI(item.ckName) }}</span>
          <br />
          <span>区域名称： {{ decodeURI(item.areaName) }}</span>
          <br />
          <span>储位名称： {{ decodeURI(item.cwName) }}</span>
          <br />
          <span>储位容量： {{ decodeURI(item.storageCapacity) }}</span>
          <br />
        </div>
      </div>
    </div>
  </a-modal>
  <a-drawer
    ok-text="关闭"
    :hide-cancel="true"
    :drawer-style="{ zIndex: 999 }"
    :mask-closable="false"
    :width="400"
    height="100%"
    popup-container=".main-base-style"
    :visible="pageData2.showAdd"
    placement="bottom"
    unmountOnClose
    @ok="sideNo1"
    :closable="false"
  >
    <template #title> 储位设定 </template>
    <div class="selectCc">
      <a-button status="success" @click="openQRcodes1">储位二维码</a-button>
      <Toolbar :items="['新增', '删除']" @add="addHandler1" @del="delcwTab"> </Toolbar>
    </div>
    <a-table
      size="mini"
      :scrollbar="false"
      :max-height="pageData2.rHeight"
      page-position="bottom"
      @page-change="pagination.change"
      :columns="columns"
      :data="dataLists"
      v-model:selected-keys="selectedRowKeys1"
      :rowKey="rowKey"
      :row-selection="{ showCheckedAll: true, width: 50, onlyCurrent: true }"
      :scrollbar-always-on="false"
    >
      <template #storageName="{ record }">
        <a-input class="bacClass" placeholder="" v-model="record.storageName" />
      </template>
      <template #storageCapacity="{ record }">
        <a-input-number
          class="bacClass"
          :precision="2"
          v-model="record.storageCapacity"
          :min="0"
          :max="10000000"
        />
      </template>
      <template #storageCode="{ record }">
        <a-input class="bacClass" placeholder="" v-model="record.storageCode" />
      </template>
      <template #save="{ record }">
        <a-space>
          <a-button type="primary" @click="bcCw(record)">保存</a-button>
          <a-button type="primary" status="warning" @click="bcCw1(record)">
            <template #icon>
              <icon-edit />
            </template>
            修 改
          </a-button>
        </a-space>
      </template>
      <template #qrcodes="{ record }">
        <a-button status="success" @click="openQRcodes(record)">储位二维码</a-button>
      </template>
    </a-table>
  </a-drawer>
</template>
<script lang="ts">
  import { post } from '@/api/http'
  import { usePagination, useRowKey, useRowSelection, useTable } from '@/hooks/table'
  import { onMounted, reactive, ref, watch } from 'vue'
  
  import { Message, Modal } from '@arco-design/web-vue'
  import { FormInstance } from '@arco-design/web-vue/es/form'
  import { baseURL } from '../../../api/axios.config'
  import axios from 'axios'
  import filedownload from 'js-file-download'
  import PageTabelLayout from '@/components/pageTabelLayout.vue'
  import WHService from '@/service/wh'
  import Toolbar from '@/components/Toolbar.vue'
  import QrcodeVue from 'qrcode.vue'
  import printJS from 'print-js'
  import { localeText } from '@/api/aggridZw'
  import { ModalDialogType } from '@/types/components'
  import usePermission from '@/store/modules/permission'
  import { pagingList } from '@/api/paging'
  import { exportStyleExcel } from '@/api/Export2StyleExcel'
  import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'
  import { slicing } from '@/utils/caseFrimAndSecRig'
  interface Cloth {
    code: string
  }

  interface ClothInfo {
    id: any
    warehouseCode: any
    warehouseName: string
    shelveCode: string
    shelveName: string
    storageName: string
    storageCode: string
    remark: string
    firm: any
    typeName: string
    warehouseTypeName: string
    positionCode: any
    positionName: string
    firmName: string
    warehouseNames: any
    ckName: string
    hzName: string
  }

  export default {
    name: 'WarehouseAreademo',

    setup() {
      const permissionStore: any = usePermission()
      const whService = new WHService()
      const whList = ref<any[]>([])
      const whTypeList = whService.whTypeList
      // const whTypeFieldList = whService.whTypeFieldList
      const companyList: any = whService.companyList
      const searchData = reactive<{
        whTypeName: string
        firm: any
        wh: string
        whType: any
        firmId: any
        warehouseId: any
      }>({
        firm: '',
        whTypeName: '',
        wh: '',
        whType: '',
        firmId: null,
        warehouseId: null,
      })
      const pageData2 = reactive<{
        showAdd: boolean
        rHeight: any
      }>({
        showAdd: false,
        rHeight: 0,
      })
      const corporateRef = ref<any>()
      const corporateChange = (event: any) => {
        nextTick(() => {
          dataForm.firm = slicing(corporateRef.value.selectViewValue[0].label)
        })
      }
      // 获取公司列表
      const getCorporateList = async () => {
        try {
          pageData.corporateLoading = true
          const res = await post({ url: 'org/baCompany/getTreeCompanyByUser' })
          if (res.code == 200) {
            pageData.corporateList = res.data
            return
          }
          Message.error(res.message)
        } catch (error: any) {
          pageData.corporateLoading = false
        } finally {
          pageData.corporateLoading = false
        }
      }
      onMounted(() => {
        doRefresh()
        pageData2.rHeight = document.getElementsByClassName('main-section')[0]?.clientHeight
        //弹出层的高
        if (pageData2.rHeight !== undefined) {
          pageData2.rHeight = pageData2.rHeight - 100
        }
        console.log('pageData2.rHeight', pageData2.rHeight)
        getCorporateList()
      })
      const whChange = () => {
        whService.loadWHTypeFieldList(searchData.whTypeName, 'stockOutState')
      }
      const searchData1 = reactive<{
        whTypeName: string
        firm: any
        wh: string
        whType: any
        firmId: any
      }>({
        firm: '',
        whTypeName: '',
        wh: '',
        whType: '',
        firmId: null,
      })
      const whChange1 = () => {
        whService.loadWHTypeFieldList(searchData1.whTypeName, 'stockOutState')
      }
      const scrollbar = ref(true)

      const warehouseId1 = (res: any) => {
        dataForm.warehouseId = whList.value.find((item) => item.warehouseName == res).id
      }
      const warehouseId2 = (res: any) => {
        searchData.warehouseId = whList.value.find((item) => item.warehouseName == res).id
      }
      const tableColumns: any[] = [
        {
          dataIndex: 'firm',
          key: 'firm',
          title: '所属公司',
          width: 150,
        },
        // {
        //     dataIndex: 'warehouseTypeName',
        //     key: 'warehouseTypeName',
        //     title: '仓库类型',
        //     width: 150,
        // },
        {
          dataIndex: 'warehouseName',
          key: 'warehouseName',
          title: '仓库名称',
          width: 150,
        },
        {
          dataIndex: 'areaCode',
          key: 'areaCode',
          title: '区域编号',
          width: 150,
        },
        {
          dataIndex: 'areaName',
          key: 'areaName',
          title: '区域名称',
          width: 150,
        },
        {
          dataIndex: 'remark',
          key: 'remark',
          title: '备注',
          width: 150,
        },
        {
          title: '创建人',
          dataIndex: 'createName',
          key: 'createName',
          width: 150,
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          key: 'createTime',
          width: 150,
        },
        {
          title: '修改人',
          dataIndex: 'updateName',
          key: 'updateName',
          width: 150,
        },
        {
          title: '储位信息',
          key: 'cw',
          dataIndex: 'cw',
          slotName: 'cw',
          width: 150,
          fixed: 'right',
        },
        {
          title: '操作',
          key: 'edit',
          dataIndex: 'edit',
          slotName: 'edit',
          width: 150,
          fixed: 'right',
        },
      ]
      const columns: any = [
        {
          title: '储位名称',
          dataIndex: 'storageName',
          slotName: 'storageName',
          width: 150,
        },
        {
          title: '储位自定义代号',
          dataIndex: 'storageCode',
          slotName: 'storageCode',
          width: 150,
        },
        {
          title: '储位容量',
          dataIndex: 'storageCapacity',
          slotName: 'storageCapacity',
          width: 150,
        },
        {
          title: '储位二维码',
          key: 'qrcodes',
          dataIndex: 'qrcodes',
          slotName: 'qrcodes',
          width: 150,
        },
        {
          title: '创建人',
          key: 'createName',
          dataIndex: 'createName',
          width: 150,
        },
        {
          title: '创建时间',
          key: 'createTime',
          dataIndex: 'createTime',
          width: 200,
        },
        {
          title: '修改人',
          key: 'updateName',
          dataIndex: 'updateName',
          width: 150,
        },
        {
          title: '修改时间',
          key: 'updateTime',
          dataIndex: 'updateTime',
          width: 200,
        },
        {
          title: '操作',
          dataIndex: 'save',
          slotName: 'save',
          fixed: 'right',
        },
      ]
      const total = ref(10)
      // const page = ref(1);
      // const size = ref(5);
      function PageSize(val: any) {
        if (isIDs.value == 1) {
          pagination.page = val
          doRefresh()
        }
      }

      function change1(val: any) {
        if (isIDs.value == 1) {
          pagination.pageSize = val
          doRefresh()
        }
      }

      let tableList1 = ref([])
      let isIDs: any = ref(1)

      // 查询
      function doRefresh() {
        pageData.pageLoading = true
        updateGridState01()
        post({
          url: 'wms/Area/getAreaPage',
          data: {
            page: pagination.page,
            size: pagination.pageSize,
            deleteState: 0,
            warehouseId: searchData.warehouseId,
            firmId: searchData.firmId,
            warehouseTypeName: searchData.whTypeName,
          },
        })
          .then(({ data, code }: any) => {
            if (code === 200) {
              // table.handleSuccess(data.list);
              // pagination.setTotalSize(data.total)
              // gridOption.value.setRowData(data.total)
              // tableList1 = data.list;
              table.handleSuccess(data.list)
              gridOption.value.setRowData(data.list)
              total.value = data.total
            }
          })
          .catch(console.log)
          .finally(() => {
            pageData.pageLoading = false
          })
      }

      function doRefresh2() {
        pageData.pageLoading = true
        post({
          url: 'wms/Area/getAreaPage',
          data: {
            page: pagination.page,
            size: pagination.pageSize,
            firmId: searchData.firmId,
            warehouseTypeName: searchData.whTypeName,
          },
        })
          .then(({ data, code }: any) => {
            if (code === 200) {
              // table.handleSuccess(data.list);
              // pagination.setTotalSize(data.total)
              // gridOption.value.setRowData(data.total)
              // tableList1 = data.list;
              table.handleSuccess(data.list)
              gridOption.value.setRowData(data.list)
              total.value = data.total
            }
          })
          .catch(console.log)
          .finally(() => {
            pageData.pageLoading = false
          })
      }

      function doRefresh3() {
        pageData.pageLoading = true
        post({
          url: 'wms/Area/getAreaPage',
          data: {
            page: pagination.page,
            size: pagination.pageSize,
          },
        })
          .then(({ data, code }: any) => {
            if (code === 200) {
              // table.handleSuccess(data.list);
              // pagination.setTotalSize(data.total)
              // gridOption.value.setRowData(data.total)
              // tableList1 = data.list;
              table.handleSuccess(data.list)
              gridOption.value.setRowData(data.list)
              total.value = data.total
            }
          })
          .catch(console.log)
          .finally(() => {
            pageData.pageLoading = false
          })
      }

      const { selectedRowKeys, onSelectionChange } = useRowSelection()
      const pagination = usePagination(doRefresh)
      const table = useTable()
      const rowKey = useRowKey('id')

      interface BrandInfo {
        remark: string | undefined
        areaCode: any
        warehouseName: string
        areaName: string | undefined
        warehouseId: any
        warehouseTypeName: string | undefined
        firm: string | undefined
        id: any
        firmId: any
      }

      const dataForm = reactive<BrandInfo>({
        id: null,
        remark: '',
        areaCode: null,
        warehouseName: '',
        areaName: '',
        warehouseId: null,
        warehouseTypeName: '',
        firm: '',
        firmId: null,
      })
      const pageData = reactive<{
        clothList: Cloth[]
        showAdd: boolean
        showAdd1: boolean
        sideTitle: string
        pageLoading: boolean
        dropDownData: any
        dropDownData1: any
        fieldNameList: []
        warehouseName: string
        isEdit: boolean
        corporateList: any[]
        corporateLoading: boolean
      }>({
        clothList: [],
        showAdd: false,
        showAdd1: false,
        sideTitle: '新增仓库区域',
        pageLoading: false,
        dropDownData1: '',
        dropDownData: '',
        fieldNameList: [],
        warehouseName: '',
        isEdit: false,
        corporateList: [],
        corporateLoading: false,
      })

      // 删除
      const deleteHandler = () => {
        // console.log(gridOption.value.getSelectedRows(), '121212112');

        if (isIDs.value == 1) {
          if (gridOption.value.getSelectedRows().length === 0) {
            return
          }
          Modal.confirm({
            title: '系统提示',
            content: '确认删除选中的数据?',
            onOk() {
              post({
                url: 'wms/Area/delete',
                data: gridOption.value.getSelectedRows().map((o: any) => {
                  return o.id
                }),
              }).then(({ code, data }: any) => {
                if (code === 200) {
                  Message.success({
                    content: '删除成功',
                    duration: 5000,
                  })

                  pagination.page = 1
                  doRefresh3()
                } else {
                  Message.error({
                    content: '删除失败',
                    duration: 5000,
                  })
                }
              })
            },
          })
        }
      }
      // 查询
      const selectHandler = () => {
        // if (searchData.whTypeName == '' || searchData.wh == '' || searchData.firm == '') {
        //     Message.error('请先选择仓库和公司')
        // } else {
        //     doRefresh()
        // }
        if (searchData.firm !== '') {
          if (searchData.wh !== '') {
            // pagination.page = 1
            doRefresh()
          } else {
            // pagination.page = 1
            doRefresh2()
          }
        } else if (searchData.whTypeName !== '') {
          if (searchData.wh !== '') {
            doRefresh()
          } else {
            doRefresh2()
          }
        } else if (searchData.whTypeName == '' && searchData.wh == '' && searchData.firm == '') {
          doRefresh3()
        }
      }

      //分类查询
      function selCxAll(val: any) {
        post({
          url: 'wms/warehouse/getWarehouseByPara',
          data: { val, virtuallyState: 0 },
        }).then(({ data, code }: any) => {
          if (code === 200) {
            pageData.warehouseName = data
          }
        })
      }

      //下拉框得到焦点
      const focusSel = () => {
        selCxAll('')
      }
      //下拉数据
      const loading = ref(false)
      const handleSearch = (value: any) => {
        if (value) {
          loading.value = true
          selCxAll(value)
          loading.value = false
        }
      }

      // 添加
      const addHandler = () => {
        pageData.showAdd = true
        pageData.sideTitle = '新增仓库区域'
        for (var key in dataForm) {
          if (key === 'id') {
            dataForm[key] = null
          } else {
            dataForm[key] = ''
          }
        }
      }

      let formRef = ref<FormInstance>()
      // 提交
      const sideOk = () => {
        formRef.value?.validate().then((err) => {
          if (!err) {
            formRef.value?.validate().then((err) => {
              if (!err) {
                pageData.pageLoading = true
                if (pageData.sideTitle === '新增仓库区域') {
                  dataForm.firm = dataForm.firm
                  dataForm.firmId = dataForm.firmId
                  post({
                    url: 'wms/Area/insert',
                    data: [dataForm],
                  }).then((res: any) => {
                    if (res.code === 200) {
                      formRef.value?.resetFields()
                      pageData.showAdd = false

                      Message.success({
                        content: '新增成功',
                        duration: 5000,
                      })
                      doRefresh3()
                    } else {
                      Message.error({
                        content: res.message,
                        duration: 5000,
                      })
                    }
                  })
                } else if (pageData.sideTitle === '修改仓库区域') {
                  const dataForms = {
                    id: dataForm.id,
                    warehouseId: dataForm.warehouseId,
                    warehouseName: dataForm.warehouseName,
                    areaCode: dataForm.areaCode,
                    remark: dataForm.remark,
                    areaName: dataForm.areaName,
                    warehouseTypeName: dataForm.warehouseTypeName,
                  }
                  companyList.value.forEach((item: any) => {
                    if (item.id == dataForm.firm) {
                      dataForm.firm = item.typeName
                        ? item.typeName + '-' + item.firmName
                        : item.firmName
                    }
                  })
                  post({
                    url: 'wms/Area/update',
                    data: [dataForms],
                  })
                    .then(({ data, code, message }: any) => {
                      if (code === 200) {
                        formRef.value?.resetFields()
                        Message.success({
                          content: '修改成功',
                          duration: 5000,
                        })
                        doRefresh3()
                        pageData.showAdd = false
                      } else {
                        Message.error({
                          content: message,
                          duration: 5000,
                        })
                      }
                    })
                    .finally(() => {
                      // doRefresh()
                      pageData.pageLoading = false
                    })
                }
              }
            })
          }
        })
      }
      //修改 record（本行数据）
      const editHandler = (record: ClothInfo) => {
        for (let key in record) {
          dataForm[key] = record[key]
        }
        dataForm.id = record.id
        //侧滑栏滑出滑入
        pageData.showAdd = true
        pageData.sideTitle = '修改仓库区域'
      }

      //前端导出
      function exports() {
        if (gridOption.value.getSelectedRows().length === 0) {
          Message.error('请先勾选需导出行数据！')
          return
        }
        const header = [
          '所属公司',
          '仓库名称',
          '区域编号',
          '区域名称',
          '备注',
          '创建人',
          '创建时间',
          '修改人',
          '修改时间',
        ]
        const filterVal = [
          'firm',
          'warehouseName',
          'areaCode',
          'areaName',
          'remark',
          'createName',
          'createTime',
          'updateName',
          'updateTime',
        ]
        let data = formatJson(filterVal, gridOption.value.getSelectedRows())
        exportStyleExcel({ header, data, filename: '仓库区域管理.xlsx' })
      }

      function formatJson(filterVal: any[], jsonData: any[]) {
        return jsonData.map((v) =>
          filterVal.map((j) => {
            if (v[j]) {
              return v[j]
            } else {
              return ''
            }
          })
        )
      }

      //模板下载
      const downloadHandler = () => {
        axios
          .get(baseURL + '/wms/Area/uploadModel', {
            responseType: 'blob',
            headers: {
              token: sessionStorage.getItem('USER-TOKEN-KEY'),
            },
          })
          .then((res) => {
            if (res.status === 200) {
              filedownload(res.data, '仓库区域模板.xlsx')
            }
          })
      }
      let keyList = {
        areaId: 0,
        areaName: '',
      }
      let lengsDs: number = 0

      let keyscw: keyscwType = {
        firm: '',
        warehouseId: '',
        warehouseName: '',
        id: '',
        name: '',
        areaName: '',
      }

      interface keyscwType {
        firm: any
        warehouseId: any
        warehouseName: any
        id: any
        name: any
        areaName: any
      }

      interface dataListType {
        storageName: any
        storageCode: any
        storageCapacity: any
      }

      const dataLists = ref<dataListType[]>([
        {
          storageName: '',
          storageCode: '',
          storageCapacity: 0,
        },
      ])

      const editHandler1 = (key: any) => {
        keyList.areaId = Number(key.id)
        keyList.areaName = key.areaName
        opCwdata(keyList)
        keyscw = key
        pageData2.showAdd = true
      }

      const addHandler1 = () => {
        if (dataLists.value.length > lengsDs) {
          Message.warning('请先保存后在添加')
          return
        } else {
          dataLists.value.push({
            storageName: '',
            storageCode: '',
            storageCapacity: 0,
          })
        }
      }

      function opCwdata(key: any) {
        post({
          url: 'wms/Storage/getStorageByPara',
          data: key,
        })
          .then((res: any) => {
            if (res.code === 200) {
              dataLists.value = res.data
              lengsDs = res.data.length
            }
          })
          .catch(console.log)
      }

      const sideNo1 = () => {
        pageData2.showAdd = false
      }
      const bcCw = (key: any) => {
        if (key.createName) {
          Message.warning('该储位已存在只能修改或删除！')
          return
        } else {
          let cw = {
            firm: keyscw.firm,
            warehouseId: Number(keyscw.warehouseId),
            warehouseName: keyscw.warehouseName,
            areaId: Number(keyscw.id),
            areaName: keyscw.areaName,
            storageCapacity: key.storageCapacity,
            storageName: key.storageName,
            storageCode: key.storageCode,
          }
          post({
            url: 'wms/Storage/addStorage',
            data: [cw],
          }).then((res: any) => {
            if (res.code === 200) {
              // isHjZt.value = false
              opCwdata(keyList)
              Message.success('保存成功')
            } else {
              Message.error(res.message)
            }
          })
        }
      }
      const bcCw1 = (key: any) => {
        // isHjZt.value = true
        if (key.createName) {
          post({
            url: 'wms/Storage/updateStorage',
            data: [
              {
                id: Number(key.id),
                storageName: key.storageName,
                storageCapacity: key.storageCapacity,
                storageCode: key.storageCode,
              },
            ],
          }).then((res: any) => {
            if (res.code === 200) {
              // isHjZt.value = false
              opCwdata(keyList)
              Message.success('修改成功')
            } else {
              Message.error(res.message)
            }
          })
        } else {
          Message.error('该储位不存在，请保存后在修改!')
          return
        }
      }
      //导入
      const importHandler = () => {
        // for (var key in dataForm) {
        //     if (key === 'id') {
        //         dataForm[key] = null
        //     } else {
        //         dataForm[key] = ''
        //     }
        // }
        // //侧滑栏滑出滑入
        // pageData.showAdd1 = true
        // pageData.sideTitle = '添加表头'
        const inputEle: HTMLInputElement = document.createElement('input')
        inputEle.type = 'file'
        inputEle.id = 'fileUploadExcel'
        inputEle.accept =
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
        inputEle.addEventListener('change', (e) => {
          const formData = new FormData()
          if (inputEle.files !== null) {
            formData.append('file', inputEle.files[0] || '')
          } else {
            Message.warning('未选择文件！')
            return
          }
          pageData.pageLoading = true
          axios
            .post(baseURL + '/wms/Area/importAreaList', formData, {
              headers: {
                'Content-Type': 'multipart/form-data',
                token: sessionStorage.getItem('USER-TOKEN-KEY'),
              },
            })
            .then((result) => {
              if (result.data['code'] === 200) {
                Message.success('导入成功')
              } else {
                Message.error(result.data.message)
              }
            })
            .finally(() => {
              pageData.pageLoading = false
              doRefresh()
            })
        })
        inputEle.click()
      }
      const sideOks = () => {
        formRef.value?.validate().then((err) => {
          if (!err) {
            formRef.value?.validate().then((err) => {
              if (!err) {
                pageData.pageLoading = true
                if (pageData.sideTitle === '添加表头') {
                  const inputEle: HTMLInputElement = document.createElement('input')
                  inputEle.type = 'file'
                  inputEle.id = 'fileUploadExcel'
                  inputEle.accept =
                    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
                  inputEle.addEventListener('change', (e) => {
                    const formData = new FormData()
                    if (inputEle.files !== null) {
                      formData.append('file', inputEle.files[0] || '')
                      formData.append('warehouseId', dataForm.warehouseId)
                      formData.append('warehouseName', dataForm.warehouseName)
                    } else {
                      Message.warning('未选择文件！')
                      return
                    }

                    axios
                      .post(baseURL + '/wms/Area/analyseAreaModel', formData, {
                        headers: {
                          'Content-Type': 'multipart/form-data',
                          token: sessionStorage.getItem('USER-TOKEN-KEY'),
                          //  warehouseId: dataForm.warehouseId,
                          //     warehouseName: dataForm.warehouseName,
                        },
                      })
                      .then((result) => {
                        if (result.data['code'] === 200) {
                          Message.success('导入成功')
                        } else {
                          Message.error(result.data.message)
                        }
                      })
                      .finally(() => {
                        if (searchData.firm !== '') {
                          if (searchData.wh !== '') {
                            doRefresh()
                          } else {
                            doRefresh2()
                          }
                        } else if (searchData.whTypeName !== '') {
                          if (searchData.wh !== '') {
                            doRefresh()
                          } else {
                            doRefresh2()
                          }
                        } else if (
                          searchData.whTypeName == '' &&
                          searchData.wh == '' &&
                          searchData.firm == ''
                        ) {
                          doRefresh3()
                        }
                        pageData.pageLoading = true
                        pageData.showAdd1 = false
                      })
                  })
                  inputEle.click()
                }
              }
            })
          }
        })
      }

      // 公司下拉框 改变

      const companyChange1 = () => {
        searchData.wh = ''
        whService.getWarhouseListByFirmId(searchData.firm, searchData.whTypeName)
      }
      const companyChange = () => {
        searchData.wh = ''
        whService.getWarhouseListByFirmId(searchData1.firm, searchData1.whTypeName)
      }
      watch(
        () => whService.whList.value,
        (o, n) => {
          whList.value = whService.whList.value
          // console.log(whList.value, '6666666666666666666666666');
        }
      )
      const selectChange = () => {
        doRefresh()
      }
      //判断是否填写了中文
      const isChiese = (value: string, cb: Function) => {
        return new Promise<void>((resolve) => {
          if (window.encodeURI(value).indexOf('%') !== -1) {
            cb('填写的值不能包含中文！')
          }
          resolve()
        })
      }
      //input离开焦点 将小写转大写
      const headerShow = ref<boolean>(true)
      const inputBlur = () => {
        dataForm.areaCode = dataForm.areaCode.toUpperCase()
      }
      //仓库名称
      const ckmcFocus = () => {
        post({
          url: '/wms/warehouse/getWarehouseByPara',
          data: {
            firmId: dataForm.firmId,
            warehouseTypeName: dataForm.warehouseTypeName,
            virtuallyState: 0,
          },
        })
          .then(({ data, code }: any) => {
            if (code === 200) {
              whList.value = data
            }
          })
          .catch(console.log)
      }
      const ckmcFocus1 = () => {
        if (searchData.whTypeName == '' || searchData.firmId == '') {
          whList.value = []
          Message.error('请先选择仓库类别和公司')
          return
        } else {
          post({
            url: '/wms/warehouse/getWarehouseByPara',
            data: {
              firmId: searchData.firmId,
              warehouseTypeName: searchData.whTypeName,
              virtuallyState: 0,
            },
          })
            .then(({ data, code }: any) => {
              if (code === 200) {
                whList.value = data
              }
            })
            .catch(console.log)
        }
      }
      // 表格准备事件
      const gridOption = ref()
      const colState = ref()
      const gridReady = (params: any) => {
        gridOption.value = params.api
        colState.value = params.columnApi
      }
      const defaultColDef = {
        sortable: true,
        resizable: true,
        filter: true,
        // flex: 1
      }
      let tc: any[] = tableColumns.map((o) => {
        let obj = {
          headerName: o.title,
          field: o.key,
          pinned: o['fixed'],
        }
        if (o.slotName === 'cw') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false
          obj['lockPosition'] = 'right'
          obj['width'] = 150
          obj['cellRenderer'] = {
            template: `
                    <a-space>
                        <a-button v-if="e" type="primary" @click="a1">储位</a-button>
                    </a-space>

                    `,
            setup(props: any) {
              const isDtas = ref(props.params.data)
              const a1 = () => {
                editHandler1(props.params.data)
              }
              return {
                a1,
                isDtas,
                e: permissionStore.hasPermisson('ckqy.cw'),
              }
            },
          }
        }
        if (o.slotName === 'edit') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false
          obj['lockPosition'] = 'right'

          obj['cellRenderer'] = {
            template: `
                    <a-space>
                              <a-button type="primary" size="small" v-if="e" status="warning" @click="a"
                                >
                                <template #icon>
                                    <icon-edit />
                                </template>
                                修 改
                                </a-button>
                                <a-button v-if="e1" status="success" size="mini" @click="a2">查看二维码</a-button>
                            </a-space>  `,
            setup(props: any) {
              const a = () => {
                editHandler(props.params.data)
              }
              const a2 = () => {
                openQRcode(props.params.data)
              }
              return {
                a,
                a2,
                e: permissionStore.hasPermisson('ckqy.xg'),
                e1: permissionStore.hasPermisson('ckqy.ckewm'),
              }
            },
          }
        }

        return obj
      })
      let a = [
        {
          showRowGroup: 'hide_def',
          headerName: '',
          checkboxSelection: true,
          headerCheckboxSelection: true,
          pinned: 'left',
          width: 50,
          resizable: false,
          filter: false,
          sortable: false,
          minWidth: 50,
          maxWidth: 50,
          lockPosition: 'left',
        },
      ]
      tc = a.concat(tc)
      //生成条码
      let qrData: any = reactive({
        firmName: '',
        department: '',
        zu: '',
        username: '',
        staffCode: '',
        nickName: '',
      })
      const visible = ref(false)

      const handleOk = () => {
        printJS({
          printable: 'warehouse',
          type: 'html',
          targetStyles: ['*'],
        })
        visible.value = false
      }
      const handleCancel = () => {
        visible.value = false
      }

      const openQRcode = (item: any) => {
        visible.value = true
        console.log(item)
        qrData.gcName = item.firm
        qrData.ckName = item.warehouseName
        qrData.areaCode = item.areaCode
        qrData.ckType = item.warehouseTypeName
        qrData.areaName = item.areaName
        qrData.code = JSON.stringify({
          areaId: item.id,
          warehouseId: item.warehouseId,
        })
      }
      const printList: any = ref([])
      const openQRcodes = (item: any) => {
        if (item.id == null || item.id == undefined || item.id == '') {
          Message.warning('请先保存储位！')
          return
        }
        printList.value = []
        visible1.value = true
        post({
          url: 'wms/Storage/printStorage',
          data: [item.id],
        }).then((res: any) => {
          if (res.code == 200) {
            res.data.forEach(function (o: any) {
              var printData = {
                ckName: '',
                gcName: '',
                code: '',
                areaName: '',
                storageCapacity: '',
                cwName: '',
              }
              printData.gcName = o.firm
              printData.ckName = o.warehouseName
              printData.areaName = o.areaName
              printData.cwName = o.storageName
              printData.storageCapacity = o.storageCapacity
              printData.code = JSON.stringify({
                warehouseId: o.warehouseId,
                area: o.areaId,
                storageCapacity: o.storageCapacity,
                storageId: o.storageId,
              })
              printList.value.push(printData)
            })
          } else {
            Message.error(res.message)
          }
        })
      }

      const localeText1: any = ref(localeText)
      const visible1 = ref(false)
      const print1 = () => {
        printJS({
          printable: 'storagePrint',
          type: 'html',
          targetStyles: ['*'],
        })
        visible1.value = false
      }
      const handleCancel1 = () => {
        visible1.value = false
      }
      let selectedRowKeys1 = ref([])
      const openQRcodes1 = () => {
        if (selectedRowKeys1.value.length == 0) {
          Message.warning('请先勾选')
          return
        }
        printList.value = []
        post({
          url: 'wms/Storage/printStorage',
          data: selectedRowKeys1.value,
        }).then((res: any) => {
          if (res.code == 200) {
            selectedRowKeys1.value = []
            res.data.forEach(function (o: any) {
              var printData = {
                ckName: '',
                gcName: '',
                code: '',
                areaName: '',
                storageCapacity: '',
                cwName: '',
              }
              printData.gcName = o.firm
              printData.ckName = o.warehouseName
              printData.areaName = o.areaName
              printData.cwName = o.storageName
              printData.storageCapacity = o.storageCapacity
              printData.code = JSON.stringify({
                warehouseId: o.warehouseId,
                area: o.areaId,
                storageCapacity: o.storageCapacity,
                storageId: o.storageId,
              })
              printList.value.push(printData)
            })
            visible1.value = true
          } else {
            Message.error(res.message)
          }
        })
      }
      const delcwTab = () => {
        if (selectedRowKeys1.value.length === 0) {
          return
        }
        let isArray: any = []
        selectedRowKeys1.value.forEach((item) => {
          isArray.push(Number(item))
        })
        console.log(isArray)
        Modal.confirm({
          title: '系统提示',
          content: '确认删除选中的数据?',
          onOk() {
            // console.log(selectedRowKeys.value.values)
            post({
              url: 'wms/Storage/delStorage',
              data: isArray,
            }).then(({ code, data, message }: any) => {
              if (code === 200) {
                opCwdata(keyList)
                Message.success({
                  content: '删除成功',
                  duration: 5000,
                })
              } else {
                Message.error({
                  content: message,
                  duration: 5000,
                })
              }
            })
          },
        })
      }
      const pagingList1: any = ref(pagingList)
      const { saveGridState: saveGridState01, updateGridState: updateGridState01 } =
        saveOrUpdateGridState01('WarehouseAreademo-1', gridOption, colState, tc)
      const onColumnMoved = () => {
        saveGridState01()
      }
      const onColumnResized = () => {
        saveGridState01()
      }
      const onColumnVisible = () => {
        saveGridState01()
      }
      return {
        saveOrUpdateGridState01,
        saveGridState01,
        updateGridState01,
        onColumnMoved,
        onColumnResized,
        onColumnVisible,
        colState,
        pagingList1,
        selectedRowKeys1,
        openQRcodes1,
        printList,
        handleCancel1,
        total,
        localeText1,
        visible,
        visible1,
        handleCancel,
        handleOk,
        qrData,
        tc,
        defaultColDef,
        gridReady,
        importHandler,
        ckmcFocus1,
        ckmcFocus,
        handleSearch,
        focusSel,
        loading,
        warehouseId1,
        warehouseId2,
        sideOk,
        sideOks,
        selectHandler,
        addHandler,
        selectedRowKeys,
        pagination,
        tableColumns,
        table,
        dataForm,
        getCorporateList,
        corporateChange,
        corporateRef,
        rowKey,
        pageData,
        searchData,
        searchData1,
        exports,
        downloadHandler,
        deleteHandler,
        whChange,
        companyChange1,
        companyChange,
        whTypeList,
        companyList,
        formRef,
        whList,
        inputBlur,
        isChiese,
        isIDs,
        scrollbar,
        selectChange,
        headerShow,
        PageSize,
        change1,
        editHandler,
        editHandler1,
        sideNo1,
        pageData2,
        addHandler1,
        bcCw,
        bcCw1,
        dataLists,
        columns,
        openQRcodes,
        print1,
        delcwTab,
        permissionStore,
      }
    },
    components: { PageTabelLayout, Toolbar, QrcodeVue },
  }
</script>
<style scoped lang="less">
  .cwTitle {
    width: 100%;
    display: flex;
    justify-content: space-between;
  }

  .selectCc {
    width: 100%;
    text-align: right;
    margin-right: 20px;
    margin-bottom: 10px;
  }

  .selectCc {
    width: 100%;
    text-align: right;
    margin-right: 20px;
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
  }

  :deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
  }

  :deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
  }
</style>
